package P321_拼接最大数_超时;

import java.util.*;
import java.util.ArrayList;

/**
 * 321. 拼接最大数
 * 给定长度分别为 m 和 n 的两个数组，其元素由 0-9 构成，表示两个自然数各位上的数字。现在从这两个数组中选出 k (k <= m + n) 个数字拼接成一个新的数，要求从同一个数组中取出的数字保持其在原数组中的相对顺序。
 * <p>
 * 求满足该条件的最大数。结果返回一个表示该最大数的长度为 k 的数组。
 * <p>
 * 说明: 请尽可能地优化你算法的时间和空间复杂度。
 * <p>
 * 示例 1:
 * <p>
 * 输入:
 * nums1 = [3, 4, 6, 5]
 * nums2 = [9, 1, 2, 5, 8, 3]
 * k = 5
 * 输出:
 * [9, 8, 6, 5, 3]
 * 示例 2:
 * <p>
 * 输入:
 * nums1 = [6, 7]
 * nums2 = [6, 0, 4]
 * k = 5
 * 输出:
 * [6, 7, 6, 0, 4]
 * 示例 3:
 * <p>
 * 输入:
 * nums1 = [3, 9]
 * nums2 = [8, 9]
 * k = 3
 * 输出:
 * [9, 8, 9]
 */
public class Solution {
    //思路，先构造map， Key是值，value是ArrayList，是原始的Index
    int[] maxNums;
    int originalK;
    // HashMap<Integer, Integer> kMaxMap = new HashMap<>();
    HashMap<Integer, ArrayList<Integer>> map1 = new HashMap<>(10);
    HashMap<Integer, ArrayList<Integer>> map2 = new HashMap<>(10);

    public int[] maxNumber(int[] nums1, int[] nums2, int k) {
        this.originalK = k;
        maxNums = new int[k];
        for (int i = 0; i < k; i++) {
            maxNums[i] = Integer.MIN_VALUE;
        }
        map1 = new HashMap<>(10);
        map2 = new HashMap<>(10);
        ArrayList<Integer> queue;
        for (int i = 0; i < nums1.length; i++) {
            queue = map1.getOrDefault(nums1[i], new ArrayList<>());
            queue.add(i);
            map1.put(nums1[i], queue);
        }
        for (int i = 0; i < nums2.length; i++) {
            queue = map2.getOrDefault(nums2[i], new ArrayList<>());
            queue.add(i);
            map2.put(nums2[i], queue);
        }

        //用bfs，广度优先遍历，判断之后剪枝。如果find嵌套执行，是dfs，每次会额外遍历非常多的时间
        LinkedList<int[]> curLevelList = new LinkedList<>();
        LinkedList<int[]> tmpLevelList = new LinkedList<>();

        int[] first = new int[]{0, 0, k};
        curLevelList.add(first);
        int[] eachTry;
        int levelMax = -1;
        int curLevel = k;
        //TODO 还是超时！！！！！！ 长的时候，bfs，同一level太多了
        //前面几个全是9，全是相同的，没法剪枝
        while (curLevel > 0 && !curLevelList.isEmpty()) {
            //拿到每个分支的下一步最大的首位值
            //抛掉不是最大的那部分，比如两个8，三个7，抛去首位是7的那些
            while ((eachTry = curLevelList.pollFirst()) != null) {
                curLevel = eachTry[2];
                int[][] ret = biggestNumber(nums1, nums2, eachTry[0], eachTry[1], curLevel);
                //每个ret中可能存在1到2种分支
                if (ret[0][0] == ret[1][0]) {
                    if (ret[0][0] < levelMax) {
                        //都没有当前最大的levelMax大，剪枝
                        continue;
                    }
                    if (ret[0][0] > levelMax) {
                        //比现在的还大，需要把当前存起来的全部剪枝
                        tmpLevelList.clear();
                        levelMax = ret[0][0];
                    }
                    //添加分支进去
                    tmpLevelList.add(new int[]{ret[0][1] + 1, eachTry[1], curLevel - 1});
                    tmpLevelList.add(new int[]{eachTry[0], ret[1][1] + 1, curLevel - 1});
                } else if (ret[0][0] > ret[1][0]) {
                    if (ret[0][0] < levelMax) {
                        continue;
                    }
                    if (ret[0][0] > levelMax) {
                        tmpLevelList.clear();
                        levelMax = ret[0][0];
                    }
                    tmpLevelList.add(new int[]{ret[0][1] + 1, eachTry[1], curLevel - 1});
                } else {
                    if (ret[1][0] < levelMax) {
                        continue;
                    }
                    if (ret[1][0] > levelMax) {
                        tmpLevelList.clear();
                        levelMax = ret[1][0];
                    }
                    tmpLevelList.add(new int[]{eachTry[0], ret[1][1] + 1, curLevel - 1});
                }

            }
            maxNums[k - curLevel] = levelMax;
            if(curLevel <= 1){
                //到最后一层了
               break;
            }
            levelMax = -1;
            curLevelList.addAll(tmpLevelList);
            tmpLevelList.clear();
        }
        return maxNums;
//        return find(nums1, nums2, 0, 0, k);
    }

    //todo 超时!!! 实际为dfs，嵌套太深了，太多无用功
    public int[] find(int[] nums1, int[] nums2, int start1, int start2, int k) {
        if (k <= 0) {
            return maxNums;
        }
        int[][] ret = biggestNumber(nums1, nums2, start1, start2, k);
        if (ret[0][0] == ret[1][0]) {
            //两个情况，相同，需要继续分下去，当前给maxNums更新
            //如果比已有的maxNums中对应的值小，证明当前分支无用
            if (ret[0][0] < maxNums[originalK - k]) {
                return maxNums;
            }
            //如果给某个赋值后，后面的全部需要清空，重置
            //相等的时候，不能清除掉后面的
            if (ret[0][0] > maxNums[originalK - k]) {
                maxNums[originalK - k] = ret[0][0];
                for (int i = originalK - k + 1; i < k; i++) {
                    maxNums[i] = Integer.MIN_VALUE;
                }
            }
            k--;
            //如果是从nums1中获取这个数据
            //TODO 超时！！！  递归导致每次都重复计算子部分
            //TODO 是否可以 bfs，每一层比较，剪枝
            int[] ret1 =
                    find(nums1, nums2, ret[0][1] + 1, start2, k);
            //如果是从num2中获取这个数据
            int[] ret2 =
                    find(nums1, nums2, start1, ret[1][1] + 1, k);
            return isGreaterThan(ret1, ret2) ? ret1 : ret2;
        } else if (ret[0][0] > ret[1][0]) {
            if (update(k, ret[0][0])) {
                k--;
                return find(nums1, nums2, ret[0][1] + 1, start2, k);
            } else {
                return maxNums;
            }
        } else {
            //抛弃nums1对应的分支
            //如果比已有的maxNums中对应的值小，证明当前分支无用
            if (update(k, ret[1][0])) {
                k--;
                return find(nums1, nums2, start1, ret[1][1] + 1, k);
            } else {
                return maxNums;
            }
        }
    }

    public boolean update(int k, int value) {
        //相等的时候也不能抹零后面的
        if (value < maxNums[originalK - k]) {
            return false;
        } else if (value == maxNums[originalK - k]) {
            //如果相同，虽然不清除后面的，但是还需要返回true，继续遍历
            return true;
        }
        maxNums[originalK - k] = value;
        for (int i = originalK - k + 1; i < originalK; i++) {
            maxNums[i] = Integer.MIN_VALUE;
        }
        return true;

    }

    public boolean isGreaterThan(int[] nums1, int[] nums2) {
        for (int i = 0; i < nums1.length; i++) {
            if (nums1[i] < nums2[i]) {
                return false;
            }
        }
        return true;
    }

    //每次分裂成多个选项，每个组合里面需要找到maxNums中当前可用的最大数值
    public int[][] biggestNumber(int[] nums1, int[] nums2, int nums1Start, int nums2Start, int kRemains) {
        int[][] ret = new int[][]{{-1, -1}, {-1, -1}};
        for (int i = 9; i >= 0; i--) {
            if (map1.containsKey(i)) {
                //如果有这个值，找出他所有的index，判断是否合理
                int index = binarySearchFirstBiggerNumber(map1.get(i), nums1Start);
                if (index > -1) {
                    if (nums1.length - index + nums2.length - nums2Start >= kRemains) {
                        //ok 剩余的还够
                        ret[0][0] = i;
                        ret[0][1] = index;
                        //同时补充ret[1][0],ret[1][1],如果有的话，也就是如果当前nums1中最大的有8满足，看看nums2中是否有满足的
                        int otherIndex = binarySearchFirstBiggerNumber(map2.get(i), nums2Start);
                        if (otherIndex > -1 && (nums2.length - otherIndex + nums1.length - nums1Start >= kRemains)) {
                            ret[1][0] = i;
                            ret[1][1] = otherIndex;
                        }
                        return ret;
                    }
                }
            }
            if (map2.containsKey(i)) {
                int index = binarySearchFirstBiggerNumber(map2.get(i), nums2Start);
                if (index > -1) {
                    if (nums2.length - index + nums1.length - nums1Start >= kRemains) {
                        //ok 剩余的还够
                        ret[1][0] = i;
                        ret[1][1] = index;
                        //同时补充ret[0][0],ret[0][1],如果有的话，也就是如果当前nums2中最大的有8满足，看看nums1中是否有满足的
                        int otherIndex = binarySearchFirstBiggerNumber(map1.get(i), nums1Start);
                        if (otherIndex > -1 && (nums1.length - otherIndex + nums2.length - nums2Start >= kRemains)) {
                            ret[0][0] = i;
                            ret[0][1] = otherIndex;
                        }
                        return ret;
                    }
                }


            }
        }
        //会走到这里吗？
        return ret;
    }

    //找到list中第一个比target大的数的index
    public int binarySearchFirstBiggerNumber(ArrayList<Integer> list, int target) {
        if (list == null) {
            return -1;
        }
        int low = 0, high = list.size() - 1;
        int mid, cur, lastOkIndex = -1;
        while (low <= high) {
            mid = (low + high) >>> 1;
            cur = list.get(mid);
            if (cur == target) {
                return cur;
            } else if (cur > target) {
                lastOkIndex = cur;
                high = mid - 1;
            } else {
                low = mid + 1;
            }

        }
        return lastOkIndex;
    }

    public static void main(String args[]) {
        System.out.println(Arrays.toString(new P321_拼接最大数_超时.Solution().maxNumber(new int[]{
                3,4,6,5},
                new int[]{9,1,2,5,8,3}, 5)));
        System.out.println(Arrays.toString(new P321_拼接最大数_超时.Solution().maxNumber(new int[]{8,9,7,3,5,9,1,0,8,5,3,0,9,2,7,4,8,9,8,1,0,2,0,2,7,2,3,5,4,7,4,1,4,0,1,4,2,1,3,1,5,3,9,3,9,0,1,7,0,6,1,8,5,6,6,5,0,4,7,2,9,2,2,7,6,2,9,2,3,5,7,4,7,0,1,8,3,6,6,3,0,8,5,3,0,3,7,3,0,9,8,5,1,9,5,0,7,9,6,8,5,1,9,6,5,8,2,3,7,1,0,1,4,3,4,4,2,4,0,8,4,6,5,5,7,6,9,0,8,4,6,1,6,7,2,0,1,1,8,2,6,4,0,5,5,2,6,1,6,4,7,1,7,2,2,9,8,9,1,0,5,5,9,7,7,8,8,3,3,8,9,3,7,5,3,6,1,0,1,0,9,3,7,8,4,0,3,5,8,1,0,5,7,2,8,4,9,5,6,8,1,1,8,7,3,2,3,4,8,7,9,9,7,8,5,2,2,7,1,9,1,5,5,1,3,5,9,0,5,2,9,4,2,8,7,3,9,4,7,4,8,7,5,0,9,9,7,9,3,8,0,9,5,3,0,0,3,0,4,9,0,9,1,6,0,2,0,5,2,2,6,0,0,9,6,3,4,1,2,0,8,3,6,6,9,0,2,1,6,9,2,4,9,0,8,3,9,0,5,4,5,4,6,1,2,5,2,2,1,7,3,8,1,1,6,8,8,1,8,5,6,1,3,0,1,3,5,6,5,0,6,4,2,8,6,0,3,7,9,5,5,9,8,0,4,8,6,0,8,6,6,1,6,2,7,1,0,2,2,4,0,0,0,4,6,5,5,4,0,1,5,8,3,2,0,9,7,6,2,6,9,9,9,7,1,4,6,2,8,2,5,3,4,5,2,4,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